package com.jsmtr.rms.utils.AOP;

import java.lang.reflect.Method;
import java.util.*;

import com.jsmtr.rms.dao.DaoService;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.RightInterceptor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author: cyx
 * @description:
 * @date: Created in 2019/4/11 23:21
 * @modified by:
 */
@Component
@Aspect
public class LogAspect {

    public String id=null;

   // @Autowired
    //LogService logService;

    @Autowired
   private DaoService dao;

    public DaoService getDao() {
        return this.dao;
    }

    public void setDao(DaoService dao) {
        this.dao = dao;
    }

    /**
     * 管理员登录方法的切入点
     */
    @Pointcut("execution(* com.jsmtr.rms.dao.*.login(..))")
    public void loginCell(){
    }



    /**
     * 登录操作(后置通知)
     * @param joinPoint
     * @param object
     * @throws Throwable
     */
    @AfterReturning(value = "loginCell()", returning = "object")
    public void loginLog(JoinPoint joinPoint, Object object) throws Throwable {
        BaseUser admin=(BaseUser)object;
        if (admin==null) {
            return;
        }
        if (joinPoint.getArgs() == null) {// 没有参数
            return;
        }
        id=admin.getId();
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取操作内容
        // String opContent = optionContent(joinPoint.getArgs(), methodName);
        // System.out.println(opContent);
        saveSystemLog(joinPoint.getArgs());
       /* Log log = new Log();
        log.setContent(opContent);
        log.setAdminId(admin.getId());
        log.setCreateDate(new Date());
        log.setOperation("登录");
        logService.insertLog(log);*/
    }

    /**
     * 添加操作日志(后置通知)
     *
     * @param joinPoint
     * @param object
     */
    public void insertLog(JoinPoint joinPoint, Object object) throws Throwable {
        // Admin admin=(Admin)
        // request.getSession().getAttribute("businessAdmin");
        SystemLog log=initSystemLog();
        // 判断参数
        if (joinPoint.getArgs() == null) {// 没有参数
            return;
        }
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取操作内容
        // String opContent = optionContent(joinPoint.getArgs(), methodName);
        // System.out.println(opContent);
        saveSystemLog(joinPoint.getArgs());
       /* Log log = new Log();
        log.setContent(opContent);
        log.setAdminId(id);;
        log.setOperation("添加");
        log.setCreateDate(new Date());
        logService.insertLog(log);*/
    }

    /**
     * 增量修改操作日志(后置通知)
     *
     * @param joinPoint
     * @param object
     * @throws Throwable
     */
    public void updateLog(JoinPoint joinPoint, Object object) throws Throwable {
        // Admin admin=(Admin)
        // request.getSession().getAttribute("businessAdmin");
        SystemLog log=initSystemLog();
        // 判断参数
        if (joinPoint.getArgs() == null) {// 没有参数
            return;
        }
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取操作内容
        // String opContent = optionContent(joinPoint.getArgs(), methodName);
        // System.out.println(opContent);
        saveSystemLog(joinPoint.getArgs());
        //JSONArray array=JSONArray.fromObject(joinPoint.getArgs());
       // System.out.println(array.toString());
        // 创建日志对象
       /* Log log = new Log();
        log.setContent(opContent);
        log.setAdminId(id);
        log.setOperation("修改");// 操作
        log.setCreateDate(new Date());
        logService.insertLog(log);*/
    }


    /**
     * 比较修改操作日志(后置通知)
     *
     * @param joinPoint
     * @param object
     * @throws Throwable
     */
    public void mergeLog(JoinPoint joinPoint, Object object) throws Throwable {
        // Admin admin=(Admin)
        // request.getSession().getAttribute("businessAdmin");
        SystemLog log=initSystemLog();
        // 判断参数
        if (joinPoint.getArgs() == null) {// 没有参数
            return;
        }
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取操作内容
       // String opContent = optionContent(joinPoint.getArgs(), methodName);
       // System.out.println(opContent);
        saveSystemLog(joinPoint.getArgs());

       // JSONArray array=JSONArray.fromObject(joinPoint.getArgs());
       // System.out.println(array.toString());
        // 创建日志对象
       /* Log log = new Log();
        log.setContent(opContent);
        log.setAdminId(id);
        log.setOperation("修改");// 操作
        log.setCreateDate(new Date());
        logService.insertLog(log);*/
    }

    /**
     * 删除操作日志(后置通知)
     *
     * @param joinPoint
     * @param object
     */
    public void deleteLog(JoinPoint joinPoint, Object object) throws Throwable {
        // Admin admin=(Admin)
        // request.getSession().getAttribute("businessAdmin");
        SystemLog log=initSystemLog();
        // 判断参数
        if (joinPoint.getArgs() == null) {// 没有参数
            return;
        }
        saveSystemLog(joinPoint.getArgs());

        // 获取方法名
        /*String methodName = joinPoint.getSignature().getName();

        StringBuffer rs = new StringBuffer();
        rs.append(methodName);
        String className = null;
        for (Object info : joinPoint.getArgs()) {
            // 获取对象类型
            className = info.getClass().getName();
            className = className.substring(className.lastIndexOf(".") + 1);
            rs.append("[参数，类型:" + className + "，值:(id:"
                    + joinPoint.getArgs()[0] + ")");
        }
        System.out.println(rs.toString())*/;
        // 创建日志对象
       /* Log log = new Log();
        log.setContent(rs.toString());
        log.setAdminId(id);
        log.setOperation("删除");// 操作
        log.setCreateDate(new Date());
        logService.insertLog(log);*/
    }

    /**
     * 查询操作日志(后置通知)
     *
     * @param joinPoint
     * @param object
     */
    public void selectLog(JoinPoint joinPoint, Object object) throws Throwable {
        // Admin admin=(Admin)
        // request.getSession().getAttribute("businessAdmin");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        BaseUser baseUser= (BaseUser) request.getSession().getAttribute(RightInterceptor.SEESION_MEMBER);
        //System.out.println(baseUser.getUname());
        if(baseUser!=null) {
            // 判断参数
            if (joinPoint.getArgs() == null) {// 没有参数
                return;
            }
            // 获取方法名

            SystemLog log = initSystemLog();
            String methodName = joinPoint.getSignature().getName();

            StringBuffer rs = new StringBuffer();
            rs.append(methodName);
            String className = null;
            String classValue=null;
            int argsIndex=0;
            Map resultMap=new LinkedHashMap();
            for (Object info : joinPoint.getArgs()) {
                // 获取对象类型
                if (info!=null){
                    className = info.getClass().getName();
                    className = className.substring(className.lastIndexOf(".") + 1);
                    resultMap.put("type"+argsIndex,className);
                    resultMap.put("val"+argsIndex,info);

                }else{
                    resultMap.put("type"+argsIndex,"null");
                    resultMap.put("val"+argsIndex,"null");

                }
                argsIndex++;
               /* rs.append("[参数，类型:" + className + "，值:(" + classValue + ")");
                if(info!=null) {

                }else{
                    rs.append("[参数，类型:" + className + "，值:(" + null + ")");
                }*/
            }
            JSONArray jsonObject=JSONArray.fromObject(joinPoint.getArgs());
           // System.out.println(jsonObject.toString());
            //JSONObject jsonObject=JSONObject.fromObject(resultMap);
            classValue=jsonObject.toString();
            //System.out.println(classValue);
            rs.append(classValue);
            log.setLogcontent(rs.toString());
            try {
                dao.saveLog(log);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 创建日志对象
       /* Log log = new Log();
        log.setContent(rs.toString());
        log.setAdminId(id);
        log.setOperation("删除");// 操作
        log.setCreateDate(new Date());
        logService.insertLog(log);*/
    }


    public void selectLogByXML(JoinPoint joinPoint,Object object) throws Throwable {
        // Admin admin=(Admin)
        // request.getSession().getAttribute("businessAdmin");

        // 判断参数
        if (joinPoint.getArgs() == null) {// 没有参数
            return;
        }
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();

        StringBuffer rs = new StringBuffer();
        rs.append(methodName);
        String className = null;
        for (Object info : joinPoint.getArgs()) {
            // 获取对象类型
            className = info.getClass().getName();
            className = className.substring(className.lastIndexOf(".") + 1);
            rs.append("[参数，类型:" + className + "，值:(id:"
                    + joinPoint.getArgs()[0] + ")");
        }
        System.out.println(rs.toString());
        // 创建日志对象
       /* Log log = new Log();
        log.setContent(rs.toString());
        log.setAdminId(id);
        log.setOperation("删除");// 操作
        log.setCreateDate(new Date());
        logService.insertLog(log);*/
    }

    public void saveSystemLog(Object[] args) {
        if (args!=null) {
            // 遍历参数对象
            for (Object info : args) {
                // 获取对象类型
                //className = info.getClass().getName();
                Object[] childArgs = null;
                if (info.getClass() == ArrayList.class) {
                    for (Object o : (ArrayList) info) {
                        childArgs = new Object[]{o};
                        saveSystemLog(childArgs);
                    }

                } else if (info.getClass() == HashMap.class) {
                    for (Object o : ((HashMap) info).keySet()) {
                        childArgs[0] = ((HashMap) info).get(o);
                        childArgs = new Object[]{o};
                        saveSystemLog(childArgs);
                    }
                } else if (info.getClass() == LinkedList.class) {
                    for (Object o : (LinkedList) info) {

                        childArgs = new Object[]{o};
                        saveSystemLog(childArgs);
                    }
                } else if (info.getClass() == LinkedHashMap.class) {
                    for (Object o : ((HashMap) info).keySet()) {
                        childArgs = new Object[]{((HashMap) info).get(o)};
                        saveSystemLog(childArgs);
                    }
                } else {
                    // rs.append(mName);
                    //className = className.substring(className.lastIndexOf(".") + 1);
                    Class clazz = info.getClass();
                    JSONObject jsonObject = JSONObject.fromObject(info);
                    SystemLog log;
                    if (clazz == DUserResume.class) {
                        log=fillDUserResumeLog((DUserResume)info);
                        log.setLogcontent(jsonObject.toString());
                    } else if (clazz == HRZZUser.class) {
                        log=fillHrzzUserLog((HRZZUser) info);
                        log.setLogcontent(jsonObject.toString());
                    } else if (clazz == ProjectInfo.class) {
                        log=fillProjectLog((ProjectInfo)info);
                        log.setLogcontent(jsonObject.toString());
                    }else if (clazz == DoBSUser.class) {
                        log=fillBSUserLog((DoBSUser)info);
                        log.setLogcontent(jsonObject.toString());
                    }else if (clazz == DoMSUser.class) {
                        log=fillMSUserLog((DoMSUser)info);
                        log.setLogcontent(jsonObject.toString());
                    }else if (clazz == DoOperationUser.class) {
                        log=fillOperationUserLog((DoOperationUser)info);
                        log.setLogcontent(jsonObject.toString());
                    }else if (clazz == CMSContent.class) {
                        log=fillCMSLog((CMSContent)info);
                    }else {
                         log=initSystemLog();
                        log.setLogtype("应聘者简历");
                        log.setLogcontent(jsonObject.toString());
                    }
                    try {
                        dao.saveLog(log);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                   // System.out.println(log.toString());
                }
            }
        }
    }


    private SystemLog fillCMSLog( CMSContent cmsContent){
        SystemLog log=initSystemLog();
        log.setLogresult(cmsContent.getIsdis());
        log.setLogcontent(cmsContent.getTitle());
        log.setLogtype("文章管理");
        return  log;
    }

    private SystemLog fillDUserResumeLog( DUserResume resume){
        SystemLog log=initSystemLog();
        log.setProid(resume.getProid());
        log.setFid(resume.getFid());
        log.setRid(resume.getId());
        log.setLogtype("应聘者简历");
        return  log;
    }



    private SystemLog fillHrzzUserLog( HRZZUser user){
        SystemLog log=initSystemLog();
        log.setRid(user.getId());
        log.setFid(user.getFid());
        log.setProid(user.getPid());
        log.setLogtype("高中职");
        return  log;
    }

    private SystemLog fillProjectLog(ProjectInfo projectInfo){
        SystemLog log=initSystemLog();
        log.setProid(projectInfo.getId());
        log.setLogtype("培训方案");
        return log;
    }
    private SystemLog fillBSUserLog( DoBSUser resume){
        SystemLog log=initSystemLog();
        log.setLogresult(resume.getResult());
        log.setLogremark(resume.getRemark());
        log.setFid(resume.getFid());
        log.setRid(resume.getId());
        log.setLogtype("笔试");
        return  log;
    }
    private SystemLog fillMSUserLog( DoMSUser resume){
        SystemLog log=initSystemLog();
        log.setFid(resume.getFid());
        log.setRid(resume.getId());
        log.setLogresult(resume.getResult());
        log.setLogremark(resume.getRemark());
        log.setRid(resume.getId());
        log.setLogtype("面试");
        return  log;
    }

    private SystemLog fillOperationUserLog( DoOperationUser resume){
        SystemLog log=initSystemLog();
        log.setLogresult(resume.getResult());
        log.setLogremark(resume.getBz());
        log.setFid(resume.getFid());
        log.setRid(resume.getUserid());
        log.setLogtype("实作");
        return  log;
    }

    private SystemLog initSystemLog(){
        SystemLog log=new SystemLog();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        BaseUser baseUser= (BaseUser) request.getSession().getAttribute(RightInterceptor.SEESION_MEMBER);
        log.setLogid(UUID.randomUUID().toString());
        log.setOperatorid(baseUser.getId());
        log.setOperatorcode(baseUser.getUcode());
        log.setOperatorname(baseUser.getUname());
        log.setOperattime(DateTools.toLenStr(new Date()));
        log.setLoginip(request.getRemoteAddr());
        log.setRequesturl(request.getRequestURI());
        return log;
    }

}
